package com.zqc.login.service;

import com.alibaba.nacos.client.utils.StringUtils;
import com.zqc.login.dao.UserRepository;
import com.zqc.login.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

@Service(timeout = 300000)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Reference
    private AuthCodeService authCodeService;

    @Override
    public boolean register(String email, String password, String code) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            return false;
        }
        if (!isRegistered(email)) {
            if (authCodeService.validate(email, code) == 0) {
                User user = new User();
                user.setEmail(email);
                user.setPassword(password);
                user.setToken(buildToken(email, password));
                userRepository.saveAndFlush(user);
                return true;
            }
        }

        return false;
    }

    /**
     * 生成Token
     * @param email
     * @param password
     * @return
     */
    private String buildToken(String email, String password) {
        String key = email + password;
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }

    @Override
    public boolean isRegistered(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        return userRepository.findByEmail(email) != null;
    }

    @Override
    public User login(String email, String password) {
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            return null;
        }
        return userRepository.findByEmailAndPassword(email, password);
    }

    @Override
    public String getEmailByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = userRepository.findByToken(token);
        if (user != null) {
            return user.getEmail();
        }
        return null;
    }
}


